import jwt from "jsonwebtoken";

export class Token {
   static #key = "secretkey";

   /**
    * 加密
    * @param  id 用户id
    * @returns token
    *
    * @description
    *    根据用户id、加密用随机字段和当前时间生成token
    */
   static Encrypt(id: string | number): string {
      return jwt.sign({ id }, this.#key, { expiresIn: 60 * 60 * 24 * 30 });
   }

   /**
    * 解密
    * @param token
    */
   static Decrypt(token: string): string | undefined {
      try {
         const data = jwt.decode(token);
         if (typeof data === "string") return data;
         return data?.id;
      } catch (e) {
         return "";
      }
   }

   /**
    * 验证 token 是否正确
    * @param {string} token 用户token
    * @return {Promise<boolean>} 返回验证结果
    */
   static Verify(token: string): Promise<boolean> {
      return new Promise((resolve, reject) => {
         jwt.verify(token, this.#key, (err, decode) => {
            if (err) {
               reject(decode);
               return resolve(false);
            }
            return resolve(true);
         });
      });
   }
}
